import { sms } from '../../api/index.js'

// pages/changeMobile/changeMobile.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    countTime: '获取验证码',
    status: false,
    mobile: '',
    currentMobile: '',
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  getSms: function() {
    const flag = this.valid()
    const { mobile} = this.data

    if (flag) {
      sms({ mobile })
      .then(res => {
        this.count()
      })
      .catch(e => {
        console.log(e, '发送短信')
      })
    }
  },

  count: function() {
    let timer = null
    let count = 60
    const {countTime} = this.data
    this.setData({
      status: true,
      countTime: count
    })
    timer = setInterval(() => {
      count--
      console.log(count, 'fff')

      if (count === 0) {
        clearInterval(timer)
        this.setData({
          status: false
        })
      }

      this.setData({
        countTime: count = count === 0 ? '获取验证码' : count
      })

    }, 1000)
  },

  change: function(e) {
    const {mobile, currentMobile} = this.data
    const {detail: {value},currentTarget:{dataset:{type}}} = e
    console.log(e)

    if (type === 'originMobile') {
      this.setData({
        mobile: value
      })
    } else if (type === 'currentMobile') {
      this.setData({
        currentMobile: value
      })
    } else if (type === 'code') {
      this.setData({
        code: value
      })
    }
    
  },

  valid: function() {
    const { mobile } = this.data

    if (!mobile) {
      return wx.showToast({
        title: '请输入当前手机号',
        icon: 'none'
      })
    }

    return true
  },

  onSubmit: function() {
    const {mobile, currentMobile, code} = this.data

    if(mobile === currentMobile) {
      return wx.showToast({
        title: '两手机号不能相同',
        icon: 'none'
      })
    }

    if (!currentMobile) {
      return wx.showToast({
        title: '请输入新手机号',
        icon: 'none'
      })
    }

    if(!code) {
      return wx.showToast({
        title: '请输入短信验证码',
        icon: 'none'
      })
    }
  }
})